package org.biojava.services.das.servlets;

/*
 *                  BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 * 
 * Created on Dec 6, 2006
 * 
 */



import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.biojava.dasobert.dasregistry.DasCoordinateSystem;
import org.biojava.services.das.dao.DasSourceManager;
import org.biojava.services.das.registry.ConfigBean;
import org.biojava.services.das.registry.DasCoordinateSystemCollector;
import org.biojava.services.das.registry.DasRegistrySql;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class OldCoordServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	ConfigBean config;
	ApplicationContext context;
	DasSourceManager dao;
	
	public OldCoordServlet(){		
	}
	
	public void init(ServletConfig sconfig)
	throws ServletException	{
		super.init(sconfig);
		

		context = new ClassPathXmlApplicationContext("config_dasregistry.xml");

		config = (ConfigBean) context.getBean("configBean");
		
		BeanFactory ctx=(new ClassPathXmlApplicationContext("SpringDAO.xml"));
		DasSourceManager dao=(DasSourceManager) ctx.getBean("dasSourceManager");
		
		
	}

	
	
	 public void destroy() {	
		super.destroy();
	// paranoid setting everything to null to avoid memory leaks...
		context = null;
		dao = null;
		config = null;
		
	}
	 
	 
	 private void describeCoords(PrintWriter pw, DasCoordinateSystem cs){
		 String org = cs.getOrganismName();
		 
		 pw.println("<h2>" + cs.toString()+"</h2>");	
		 if ( (! org.equals("")) ) {
			 org = org.replaceAll(" ","_");
			 String thumbnail = "http://www.ensembl.org/img/species/thumb_";			
			 thumbnail += org;
			 thumbnail += ".png";

			 pw.println("<img src=\""+thumbnail + "\"/>");
		 }
		 pw.println("<br/>");
		 pw.println("unique ID: <b>" + cs.getUniqueId() +"</b>");
		 pw.println("<br/>");		 
		 pw.println("authority name: <b>" + cs.getName()+"</b>");
		 pw.println("<br/>");		 		 
		 pw.println("(assembly) version: <b>" + cs.getVersion()+"</b>");
		 pw.println("<br/>");
		 pw.println("type of data: <b>"+ cs.getCategory()+"</b>");
		 pw.println("<br/>");		 
		 pw.println("organism: <b>" + cs.getOrganismName()+"</b>");
		 pw.println("<br/>");
		 if ( cs.getNCBITaxId() != 0) {
			 pw.println("NCBI taxonomy id: <a href=\"http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=" +cs.getNCBITaxId()+"\">"+cs.getNCBITaxId()+"</a>");
		 } else {
			 pw.println("NCBI taxonomy id:");
		 }
		 pw.println("<br/>");
		 pw.println("<br/>");
		 
		 // build up search string...
		 String loc =  "http://www.dasregistry.org/listServices.jsp?organism=";
		 //String loc =  "../listServices.jsp?organism=";
		 String u = cs.getOrganismName() ;
		 
		 if ( ( u == null) || ( u.equals(""))){
			 u = "any";
		 }
		 
		 u += "&CSName="+cs.getName();
		 
		 if ( (cs.getVersion() != null ) && ( ! cs.getVersion().equals("") )) {
			 u += "_"+ cs.getVersion();
		 }
		 
		 u += "&CSTypes=" + cs.getCategory();
		 u += "&capabilities=any&labels=any&cmd=find";
		 		 		 
		 String url = loc + u;			
		 
		 pw.println("<a href=\""+url+"\">show all DAS sources for this coordinate system</a>");
		 pw.println("<hr/>");
		 
	 }
	 
	 
	 private void describeCoordSys(DasCoordinateSystemCollector allCoords, PrintWriter pw, String name, String prefix){
		 
		 Iterator iter = allCoords.keySet().iterator();
		 
		 while (iter.hasNext()){
			 Integer i = (Integer) iter.next();
			 DasCoordinateSystem coordSys = (DasCoordinateSystem) allCoords.get(i);
			 //System.out.println("coordSys name " + coordSys.getUniqueId() + " " + name);
			 if ( coordSys.getUniqueId().equalsIgnoreCase(name)){
				 /// we found it!
				 describeCoords(pw,coordSys);
			 }
		 }
	

		 
	 }
	 
	public void doGet(
	            HttpServletRequest req,
	            HttpServletResponse resp
	    )
	    throws ServletException, IOException
	    {

		// System.out.println("got a get >" + req.getPathInfo()+"< " + req.getQueryString() + " | " +
	     //           " | " + req.getRequestURI() + 
	      //            " | " + req.getPathTranslated() + " | " + req.getContextPath() + " | " + req.getHeaderNames());
	        
	        
		 String cmdPath = req.getPathInfo();
	        if (cmdPath == null) {
	            cmdPath = "";
	        }
	        //System.out.println("commandPath " + cmdPath);
	        
	        StringTokenizer toke = new StringTokenizer(cmdPath, "/");
	        if (! toke.hasMoreTokens()) {
	            welcomePage(req, resp);
	            return;
	        }
		 
	        
	        DasRegistrySql registry = (DasRegistrySql) context.getBean("registryBean");
	        String prefix          = registry.getRegistryPrefix();
			DataSource ds = registry.getDataSource();

			Connection conn = null;

			try {

				conn = ds.getConnection();
				DasCoordinateSystemCollector allCoords = dao.getAllCoordinateSystemsMap(conn, prefix);
				
				
				List nameComponents = new ArrayList();
		        String command = toke.nextToken();
		        //System.out.println("got command " + command);
		        
		        resp.setContentType("text/html");
		        PrintWriter pw = resp.getWriter();
		        pw.println(getSangerHeader());    
		        pw.println("To get more information please proceed to the <a href=\"http://www.dasregistry.org/help_coordsys.jsp\">help page on coordinate systems</a>");
		        describeCoordSys(allCoords,pw,command,prefix);
		        
		        while (toke.hasMoreTokens()) {        	
		            nameComponents.add(command);
		            command = toke.nextToken();
		            // try to match the "command" to the unique name for a coordinate system
		            
		            describeCoordSys(allCoords,pw,command,prefix);
		            
		            
		        }
		        pw.println( "		 </div>");
		        pw.println("</body>");
		        pw.println("</html>");
		        pw.close();
		        pw.flush();		       				
				
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (conn != null ) {
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
	        
	        
	        
	
	    }
	 
	 private void welcomePage(HttpServletRequest req,
	            HttpServletResponse resp)
	    throws ServletException, IOException
	    {
	        resp.setContentType("text/html");
	        PrintWriter pw = resp.getWriter();
	        pw.println(getSangerHeader());      
	        pw.println("you might want to view the <a href=\"http://www.dasregistry.org/help_coordsys.jsp\">help page on coordinate systems</a>.");
	        pw.println("</div></body>");
	        pw.println("</html>");
	        pw.close();
	        pw.flush();
	    }
	 
	 
	 private String getSangerHeader(){
		 StringBuffer str = new StringBuffer();
		 str.append(
		 "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"+
"		 <!DOCTYPE html"+ 
"		      PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\""+
"		      \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"+
""+
"		 <html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">"+
"		 <head>"+
"		     <title>DAS registry coordinate system information</title>"+
"		     <link rel=\"stylesheet\"    type=\"text/css\"     href=\"http://www.dasregistry.org/stylesheet.css\" />"+
"		     <link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"http://www.dasregistry.org/favicon.ico\" />"+
"		 </head>"+
""+
"		 <body>"+
"		 <div id=\"upbg\">"+
"		 <div id=\"outer\">"+
"		 <div id=\"content\">"+
"		 <div id=\"headercontent\">"+
"		 <form method=\"post\" action=\"http://www.dasregistry.org/listServices.jsp\" name=\"count_form\">"+
"		 [ <a href=\"http://www.dasregistry.org/index.jsp\">home</a> |"+
"		   <a href=\"http://www.dasregistry.org/listServices.jsp\">list services</a> |"+
"		   <a href=\"http://www.dasregistry.org/validateServer.jsp\">validate</a> |"+
"		   <a href=\"http://www.dasregistry.org/registerService.jsp\">register new</a> |"+
"		   <a href=\"http://www.dasregistry.org/statistics.jsp\">statistics</a> |"+
"		   <a href=\"http://www.dasregistry.org/help_index.jsp\">help</a> ]"+
"		   "+
"		   <input type=\"text\" name=\"keyword\" size=\"10\" value=\"\"/>"+
"		   <input type=\"hidden\" name=\"cmd\" value=\"keyword\">"+
"		   <input type=\"submit\" value=\"search\">  "+
"		 </form>"+
"        <h2>Coordinate System Information</h2></div>");
		 return str.toString();
		 
	 }

}
